package com.bilibili.juc.cf.one;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/*
AnyOf
任意一个任务执行完，就执行anyOf返回的CompletableFuture。如果执行的任务异常，anyOf的CompletableFuture，执行get方法，会抛出异常
 */
public class AnyOfFutureTwoTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        CompletableFuture<String> a = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"\t -----A come in " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("A我执行完了");
            System.out.println(Thread.currentThread().getName()+"\t -----A over " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            return "A我执行完了";
        });
        CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+"\t -----B come in " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("B我执行完了");
            System.out.println(Thread.currentThread().getName()+"\t -----B over " + DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            return "B我执行完了";
        });
        CompletableFuture<Object> anyOfFuture = CompletableFuture.anyOf(a, b).whenComplete((result,ex)->{
            System.out.println("finish");
            System.out.println("result=>"+result);
//            return "捡田螺的小男孩";
        });
        System.out.println("anyOfFuture.join()==> " + anyOfFuture.join());
        for (int i = 0 ; i < 5;i++){
            System.out.println(" 主程序正在执行其它的任务"+i);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
